#include "tcp_server.h"

using namespace uvpp;

TCPServer::TCPServer(EventLoop* loop, bool noDelay /* = true */)
	:_loop(loop),
	_noDelay(noDelay),
	_newConnectionCallback(nullptr),
	_closeConnecitonCallback(nullptr)
{

}

TCPServer::~TCPServer()
{

}

int TCPServer::bindAndListen(InetAddress& address)
{
	_acceptor = std::make_shared<TCPAcceptor>(_loop, _noDelay);
	int ret = _acceptor->bind(address);
	if (ret != 0)
	{
		return ret;
	}

	_acceptor->setNewConnectionCallback(std::bind(&TCPServer::onAccept, this, std::placeholders::_1, std::placeholders::_2));
	return _acceptor->listen();
}

void TCPServer::setNewConnectionCallback(OnConnectionStatusCallback callback)
{
	_newConnectionCallback = callback;
}

void TCPServer::setCloseConnectionCallback(OnConnectionStatusCallback callback)
{
	_closeConnecitonCallback = callback;
}

void TCPServer::setMessageCallback(OnMessageCallback callback)
{
	_onMessageCallback = callback;
}

void TCPServer::onAccept(EventLoop* loop, TCPPtr client)
{
	std::string name;
	auto connection = std::make_shared<TCPConnection>(loop, name,client);
	if (connection)
	{
		connection->setMessageCallback(_onMessageCallback);

		addConnection(name, connection);

		if (_newConnectionCallback)
		{
			_newConnectionCallback(connection);
		}
	}
	else
	{
		// log
	}
}

void TCPServer::addConnection(std::string& name, TCPConnectionPtr connection)
{
	_connectionMap.insert(std::pair<std::string, TCPConnectionPtr>(std::move(name), connection));
}

void TCPServer::removeConnection(std::string& name)
{
	_connectionMap.erase(name);
}

TCPConnectionPtr TCPServer::getConnection(const std::string& name)
{
	auto connection = _connectionMap.find(name);
	if (connection == _connectionMap.end())
	{
		return nullptr;
	}

	return connection->second;
}

void TCPServer::closeConnection(std::string& name)
{
	auto connection = getConnection(name);
	if (connection != nullptr)
	{
		connection->
	}
}